//
//  ChartWeekView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 05.04.25.
//

import SwiftUI
import Charts

struct ChartDateMonthView: View {
    
    @Binding private var date: Date
    @Binding var categoryType: CategoryType
    @StateObject var viewModel: ChartDateViewModel
    
    init(date: Binding<Date>, categoryType: Binding<CategoryType>, parentCategory: AccountingCategory? = nil) {
        _date = date
        _categoryType = categoryType
        if parentCategory == nil {
            _viewModel = StateObject(wrappedValue: ChartDateViewModel())
        } else {
            _viewModel = StateObject(wrappedValue: ChartDateSubViewModel().setCategory(category: parentCategory))
        }
    }
    
    var body: some View {
        ChartDateBaseView(
            date: $date,
            dateType: .month,
            categoryType: $categoryType,
            totalAmount: $viewModel.totalAmount,
            averageAmount: $viewModel.averageAmount,
            trendData: $viewModel.trendData,
            pieData: $viewModel.pieData,
            koiPieData: $viewModel.koiPieData,
            categoryAmountList: $viewModel.categoryAmountList,
            category: $viewModel.category,
            loadData: { date in
                loadData(date: date)
            }
        )
        .onAppear {
            loadData(date: date)
        }
    }
    
    private func loadData(date: Date) {
        viewModel.loadData(date: date, categoryType: categoryType, dateType: .month)
    }
}

@available(iOS 18.0, *)
#Preview {
    @Previewable @State var date: Date = Date()
    @Previewable @State var categoryType: CategoryType = .expense
    ChartDateMonthView(date:$date, categoryType: $categoryType)
}
